<?php

namespace app\base\model\goods;

use app\base\model\user\{UserAccount, UserAccountLog};
use think\Model;

class GoodsGroupJoinInfo extends Model
{

    // 关闭自动写入时间戳
    protected $autoWriteTimestamp = false;

    protected $table = 'xy_goods.xy_goods_group_join_info';

    //获取支持过我的人
    public static function getSupportMeListByUserId($user_id)
    {
        //获取我的发起列表
        $my_initiate_items = GoodsGroupInfo::getInitiateListByUserId($user_id);
        $list = [];
        if ($my_initiate_items) {
            $group_ids = array_column($my_initiate_items, 'group_id');
            //获取支持过我的人
            $user_ids = self::whereIn('group_id', $group_ids)->column('user_id');
            $user_ids = array_diff(array_unique($user_ids), [$user_id]);
            $list = GoodsGroupInfo::getInitiateDetailListByUserIds([
                'g.group_state' => GoodsGroupInfo::GROUP_RUN_STATE,
                'g.user_id' => ['in', $user_ids]
            ]);
        }

        return $list;
    }

    //获取我支持过的人
    public static function getISupportListByUserId($user_id, $page, $size)
    {
        $list = [];
        $group_ids = self::whereIn('user_id', $user_id)->column('group_id');
        if ($group_ids) {
            $group_ids = array_unique($group_ids);
            $list = GoodsGroupInfo::getInitiateDetailListByGroupIds($group_ids, ['g.create_time' => 'desc'], $page, $size);
        }

        return $list;
    }

    public static function getGroupJoinUserInfo($group_id)
    {
        $items = self::alias('j')
            ->join('xy_user.xy_user u', 'j.user_id=u.user_id')
            ->field('j.user_id,j.get_gold_num,j.create_time,u.nick_name,u.gender,u.small_avatar_url as avatar_url')
            ->where('j.group_id', $group_id)
            ->order('j.join_id', 'desc')
            ->select();

        if ($items) {
            array_walk($items, function (&$item) use ($group_id) {
                $item['get_gold_num'] = (float)$item['get_gold_num'];
                $item['create_time'] = date('n-j H:i', strtotime($item['create_time']));
                //判断这单是不是这个用户首次支持
                $support_log = UserAccountLog::isFirstSupport($item['user_id'], $group_id);
                $item['is_first'] = $support_log ? 1 : 0;
            });
        }

        return $items;
    }

    public static function getGroupJoinUserInfoByUserId($group_id, $user_id)
    {
        return self::field('join_id,user_id,get_gold_num,create_time')->where('group_id', $group_id)->where('user_id', $user_id)->find();
    }

    public static function hadSupport($user_id)
    {
        $join_id = self::where('user_id', $user_id)->limit(1)->value('join_id');

        return $join_id ? true : false;
    }

}